import json
import requests
import logging
from openai import OpenAI, api_key

logging.basicConfig(
    level=logging.DEBUG,  # 设置日志级别，这里设置为DEBUG，意味着会输出DEBUG及以上级别的所有日志
    format='%(asctime)s - %(levelname)s - %(message)s',  # 定义日志格式，包括时间戳、日志级别和日志消息
    datefmt='%Y-%m-%d %H:%M:%S'  # 定义时间戳的格式
)

def load_config(file_path):
    with open(file_path, 'r') as file:
        config = json.load(file)
    return config

def load_prompt(prompt_path="data/default_prompt.txt"):
    with open(prompt_path, "r", encoding="utf-8") as file:
        prompt = file.read()
    return prompt

def chat_by_openai(stream=False, model="deepseek-chat", base_url="https://api.deepseek.com", api_key=None):
    # 加载提示词
    prompt = load_prompt()
    if prompt is None:
        logging.error("提示词加载失败")
        return None
    logging.debug(f"开始调用 {model}，stream={stream}")
    client = OpenAI(api_key=api_key, base_url=base_url)
    response = client.chat.completions.create(
        model=model,
        messages=[
            {"role": "user", "content": prompt},
        ],
        stream=stream
    )
    logging.debug(f"调用成功！content 输出：{response.choices[0].message.content}")
    return response.choices[0].message.content

def get_access_token(API_KEY, SECRET_KEY):
    """
    使用 AK，SK 生成鉴权签名（Access Token）
    :return: access_token，或是None(如果错误)
    """
    url = "https://aip.baidubce.com/oauth/2.0/token"
    params = {"grant_type": "client_credentials", "client_id": API_KEY, "client_secret": SECRET_KEY}
    return str(requests.post(url, params=params).json().get("access_token"))


def chat_by_baidu(API_KEY=None, SECRET_KEY=None):
    prompt = load_prompt()
    if prompt is None:
        logging.error("提示词加载失败")
        return None
    url = ("https://aip.baidubce.com/rpc/2.0/ai_custom/v1/wenxinworkshop/chat/yi_34b_chat?access_token="
           + get_access_token(API_KEY, SECRET_KEY))

    payload = json.dumps({
        "messages": [
            {"role":"user", "content": prompt},
        ]
    }, ensure_ascii=False)

    headers = {
        'Content-Type': 'application/json'
    }

    response = requests.request("POST", url, headers=headers, data=payload.encode("utf-8"))

    response_json = json.loads(response.text)
    result = response_json.get("result")

    logging.info(f"百度模型输出：{result}")
    return json.dumps(result)


def get_internship_daily_list(model_type="openai"):
    """
    :param model_type:  选择使用集成了 openai 库的模型还是单独请求的百度模型
        openai 使用集成了 openai 库的模型
        baidu  单独请求的百度模型
    :return:
    """
    # 先加载配置文件
    config = load_config("config/config.json")

    if model_type == "openai":
        # DeepSeek
        api_key=config.get("deepseek", {}).get("api_key")
        model=config.get("deepseek", {}).get("model")
        baseURL=config.get("deepseek", {}).get("base_url")

        # moonshot
        # api_key=config.get("moonshot", {}).get("api_key")
        # model=config.get("moonshot", {}).get("model")
        # baseURL=config.get("moonshot", {}).get("base_url")

        response = chat_by_openai(api_key=api_key, model=model, base_url=baseURL)
    else:
        api_key=config.get("baidu", {}).get("api_key")
        secret_key=config.get("baidu", {}).get("secret_key")
        response = chat_by_baidu(API_KEY=api_key, SECRET_KEY=secret_key)

    logging.info(f"大模型的输出：{response}")

    # 将 response 作为 json 字符串解析保存
    data = json.loads(response)

    file_path = "data/internship_daily_list.json"
    with open(file_path, "w", encoding="utf-8") as file:
        json.dump(data, file, ensure_ascii=False)
    logging.debug(f"实习日志已经生成至：{file_path}")

    # 同时给外部的 main 函数也返回一遍
    return data


if __name__ == '__main__':
    get_internship_daily_list(model_type="baidu")
